﻿using System;
using System.IO;
using System.Net;

namespace QSearcher.QCrawler
{
    class Downloader
    {
        public void Run(int index)
        {
            FrmCrawler.T.SendMsg("开始获取下载链接......");
            var resUrl = BizLayer.Self.GetDownloadUrl();
            if (resUrl.Code != 0)
            {
                FrmCrawler.T.SendMsg("未获取到有效下载链接.");
                return;
            }
            FrmCrawler.T.SendMsg("获取到有效下载链接.");

            string tag = "";
            try
            {
                FrmCrawler.T.SendMsg("开始下载......");
                WebClient client = new WebClient();
                client.Headers.Add("User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                string file = Crawler.UrlToPath(resUrl.Url);
                file = "Downloads" + Path.DirectorySeparatorChar + file;
                Crawler.CheckDirectory(file);
                client.DownloadFile(resUrl.Url, file);
            }
            catch (Exception e)
            {
                tag = e.Message;
            }

            BizLayer.Self.SendDownloadResult(new BizLayer.DownloadResult()
            {
                ID = resUrl.ID,
                Msg = tag,
            });
            FrmCrawler.T.SendMsg("下载完成.");
        }
    }
}
